/*
  1. Promise 就是一个类 在执行这个类的时候 需要传递一个执行器进去 执行器会立即执行

  2. Promise 中有三种状态 分别为：成功 fulfilled 失败 rejected 等待 pending
    pending -> fulfilled
    pending -> rejected  
    一旦状态确定就不可更改

  3. resolve和reject函数是用来更改状态的
    resolve：fulfilled
    reject：rejected

  4. then方法内部做的事情就是判断状态 如果状态时成功 调用成功的回调函数 如果状态时失败， 调用失败的回调方法, 
    then方法时被定义原型对象上的方法

  5. then成功回调有一个参数 表示成功之后的值 then失败回调有一个参数 表示失败后的原因
  
*/
const MyPromise = require("./myPromise.js");

const promise = new MyPromise((resolve, reject) => {
  /* setTimeout(() => {
    resolve("成功");
  }, 2000); */

  resolve("成功");

  // reject("失败");
});

/* promise.then(
  (value) => {
    console.log(value);
  },
  (reason) => {
    console.log(reason);
  }
); */

/* promise.then((value) => console.log(value));
promise.then((value) => console.log(value));
promise.then((value) => console.log(value)); */

/* function other() {
  return new MyPromise((resolve, reject) => resolve("other"));
}

promise
  .then((val) => {
    console.log(val);
    return 100;
  })
  .then((val) => {
    console.log(val);
    return other();
  })
  .then((val) => console.log(val));
*/

// all
/* function p1() {
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve("p1");
    }, 200);
  });
}

function p2() {
  return new MyPromise((resolve, reject) => {
    resolve("p2");
  });
}

MyPromise.all(["a", "b", p1(), p2()]).then((val) => console.log(val)); */

// resolve
// function p1() {
//   return new MyPromise((resolve, reject) => {
//     setTimeout(() => {
//       resolve("p1");
//     }, 2000);
//   });
// }
// MyPromise.resolve(100).then((val) => console.log(val));
// MyPromise.resolve(p1()).then((val) => console.log(val));

// finally
function p1() {
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve("p1");
    }, 2000);
  });
}
function p2() {
  return new MyPromise((resolve, reject) => {
    // reject("p2 reject");
    resolve("p2 resolve");
  });
}

p2()
  .finally(() => {
    console.log("fianlly");
    return p1();
  })
  .then(
    (val) => {
      console.log(val);
    },
    (reason) => {
      console.log(reason);
    }
  );

// catch
/* function p1() {
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve("p1");
    }, 2000);
  });
}
function p2() {
  return new MyPromise((resolve, reject) => {
    // reject("p2 reject");
    resolve("p2 resolve");
  });
}

p2()
  .then((val) => console.log(val))
  .catch((reason) => console.log(reason));
 */
